<!--
* @description 
* @fileName index.vue
* @author yanghong
* @date 2020/10/30 15:01:41
!-->
<template>
    <div class="site-container">
        <div class="search-box">
            <div class="search-box-sub">
                <span class="lable-text">{{$t('site.siteName')}}</span>
                <el-input v-model="searchData.siteName" clearable></el-input>
            </div>
            <div class="search-box-sub">
                <span class="lable-text">{{$t('login.loginName')}}</span>
                <el-input v-model="searchData.userName" clearable></el-input>
            </div>
            <div class="search-box-sub">
                <span class="lable-text">{{$t('site.agentOrInstall')}}</span>
                <el-input v-model="searchData.searchFirmName" clearable></el-input>
            </div>
            <div class="search-box-sub">
                <span class="lable-text">{{$t('site.createTime')}}</span>
                <el-date-picker
                    v-model="searchData.startTime"
                    type="date"
                    :placeholder="$t('index.startTime')"
                    value-format='yyyy-MM-dd'
                    :clearable='false'
                    :picker-options="pickerOptions">
                </el-date-picker>
                <span>-</span>
                <el-date-picker
                    v-model="searchData.endTime"
                    type="date"
                    :placeholder="$t('index.endTime')"
                    value-format='yyyy-MM-dd'
                    :clearable='false'
                    :picker-options="pickerOptions">
                </el-date-picker>
            </div>
            <div class="search-box-sub">
                <el-button type="primary" @click='query' >{{$t('query')}}</el-button>
            </div>
        </div>
        
        <div class="button-box">
            <el-button type="primary" icon='el-icon-plus' @click="gotoAdd">{{$t('add')}}</el-button>
            <!-- <el-button type="primary" icon='el-icon-plus' @click="openGoogleAdd">{{$t('add')}}</el-button> -->
            <el-popconfirm
                :title="$t('index.delete_confirm')+'?'"
                :confirm-button-text="$t('sure')"
                :cancel-button-text="$t('cancel')"
                @confirm='showDeleteModal()'
                v-if='editFlag'
            >
                <el-button slot="reference" icon='el-icon-delete'>{{$t('delete')}}</el-button>
            </el-popconfirm>
        </div>
        <baseTable v-loading="loading"  row-key='sid' :data="dataRows" border  stripe @selection-change="handleSelectionChange($event)"  :column='column' :select='true'>
            <template #siteName="{data}">
                <!-- <router-link :to="{path:'overview_site', query:{ siteId: data.ids,siteName:data.siteName }}" target="_blank" class="table-link">{{data.siteName}}</router-link> -->
                <a href="javascript:;" class="hover-a-link" style="color:#ED7523;" @click="openRouter({path:'/overview_site', query:{ siteId: data.ids,siteName:data.siteName }})">{{data.siteName}}</a>
            </template>
            <template #option="{data}">
                <div class="option-box">
                    <el-button size='small' type="primary" icon="el-icon-edit" :title="$t('edit')" @click='gotoEdit(data.ids)' v-if='editFlag'></el-button>
                    <!-- <el-button size='small' type="primary" icon="el-icon-edit" :title="$t('edit')" @click='openGoogleEdit(data.ids)'></el-button> -->
                    <el-button size='small' type="primary" icon="el-icon-circle-plus-outline" :title="$t('site.relate_wifiSN')" @click='bindWifiSn(data)'></el-button>
                    <el-button size='small' type="primary" icon="el-icon-folder-add" :title="$t('site.relate_wifiSN_batch')" @click='bindWifiSnExcel(data)'></el-button>
                    
                    <el-button size='small' type="primary" icon="el-icon-notebook-2" :title="$t('device.inverter')" @click='gotoInverter(data)'></el-button>

                    <el-button size='small' type="primary" :title="$t('site.site_price')" @click='setPrice(data.ids)'><i class="iconfont icon-tag" ></i></el-button>
                    <el-button size='small' type="primary" :title="$t('device.range.title')" @click='showScope(data.ids,data)'><i class="iconfont icon-scope" ></i></el-button>
                    <el-button type="danger" v-if='editFlag && userType==5' @click='showDeleteModal(data)'  icon='el-icon-delete' :title="$t('delete')"></el-button>
                    <el-popconfirm
                        :title="$t('index.delete_item_confirm')+'?'"
                        :confirm-button-text="$t('sure')"
                        :cancel-button-text="$t('cancel')"
                        @confirm='deleteSub(data.ids)'
                        v-if='editFlag && userType!=5'
                    >
                        <el-button type="danger" slot="reference" icon='el-icon-delete' :title="$t('delete')"></el-button>
                    </el-popconfirm>
                </div>
            </template>
        </baseTable>
         <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="current"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
        <addModal @uploadPage='uploadPage' v-if='visibleAdd'></addModal>
        <editModal :editId="editId" @uploadPage='uploadPage'></editModal>
        <!-- <addModalGoogle :mapData="mapData" @uploadPage='uploadPage' ref="addModalGoogle" v-if='visibleAdd2'></addModalGoogle>
        <editModalGoogle :mapData="mapData" :editData="editData" @uploadPage='uploadPage' ref="editModalGoogle"></editModalGoogle> -->
        <bindSnModal :selRow="selRow_bind" @uploadPage='uploadPage' v-if='visibleBind'></bindSnModal>
        <bindSnExcelModal :selRow="selRow_bind2" @uploadPage='uploadPage'></bindSnExcelModal>
        <setPriceModal :siteId="setPriceId" @uploadPage='uploadPage'></setPriceModal>
        <statsScopeModal :siteId="scopeId" @uploadPage='uploadPage' :scopeData='scopeData'></statsScopeModal>
        <emailCodeModal :siteNameDelete='siteNameDelete' @deleteSub='deleteSub' :emailType='emailType' @deleteBatch='deleteBatch'></emailCodeModal>
    </div>
</template>

<script>
import emailCodeModal from './getUserEmailCode'
import baseTable from '../../components/common/baseTableNew'
import addModal from './add.vue'
import editModal from './edit.vue'
import addModalGoogle from './add_google.vue'
import editModalGoogle from './edit_google.vue'
import bindSnModal from './bind_wifiSn.vue'
import bindSnExcelModal from './bind_wifiSnExcel.vue'
import setPriceModal from './set_price.vue'
import statsScopeModal from './stats_scope'
export default {
    components:{
        baseTable,
        addModal,
        editModal,
        addModalGoogle,
        editModalGoogle,
        bindSnModal,
        bindSnExcelModal,
        setPriceModal,
        statsScopeModal,
        emailCodeModal
    },
    data () {
        return {
            mapType:localStorage.getItem('mapType'),
            businessId:this.$route.query.businessId,
            userId:this.$route.query.userId,
            pickerOptions:{ //禁用今天之后的时间
                disabledDate(time) {
                    return time.getTime() > Date.now()
                }
            },
            searchData:{
                siteName:'',
                userName:'',
                searchFirmName:'',
                startTime:'',
                endTime:'',
                currentTime:this.$options.filters['dateFormat'](new Date())
            },
            userType:JSON.parse(sessionStorage.getItem('userObj')).userType,
            editId:'',
            selRow_bind:'',
            selRow_bind2:'',
            setPriceId:'',
            scopeId:'',
            scopeData:{},
            editData:{},
            rowDataList:{},
            selectDatalist:[],
            loading:false,
            dataRows:[],
            column:[{
                title: this.$t('site.siteName'),
                value: 'siteName',
                slot: 'siteName'
            },{
                title: this.$t('user.loginName'),
                value: 'loginName'
            },{
            //     title: this.$t('site.inverterNum'),
            //     value: 'moduleNum'
            // },{
                title: this.$t('site.capacity'),
                value: 'capacity'
            },{
                title: this.$t('overview.online_inverter'),
                value: 'inverterInlineNum',
            },{
                title: this.$t('control'),
                slot: 'option',
            }],
            size:10,
            current:1,
            total:1,
            mapData:{
                width:'650px',
                height:'550px',
                crosshairFlag:false,
                zoom:6,
                center:{
                    lng:102,
                    lat:23
                },
                mapObj:{},//地图对象
                markers:[],//地图上所有的标记
            },
            editFlag:'',
            siteNameDelete:{},
            emailType:'spa',

        }
    },
    beforeCreate(){
        this.UtilsFun.createGoogle()
    },
    mounted() {
        this.getDictionaryBatch();
        this.initTable()
        this.siteGetPdtSiteManage()
    },
    computed:{
        visibleAdd2(){
            return this.$store.state.sysStore.visibleAdd2
        },
        visibleAdd(){
            return this.$store.state.sysStore.visibleAdd
        },
        visibleBind(){
            return this.$store.state.sysStore.visibleBind
        },
        userTypeNumber(){
            return localStorage.getItem('userType')
        }
    },
    methods: {
        openRouter(params){
            let url=this.$router.resolve(params)
            window.open(url.href,'_blank')
        },
        async siteGetPdtSiteManage(){
            let res = await this.API.siteGetPdtSiteManage()
            this.editFlag = res.object
        },
        gotoAdd(){
            this.$store.commit('setVisibleAdd',true)
        },
        gotoEdit(id){
            this.$store.commit('setVisibleEdit',true)
            this.editId = id
        },
        openGoogleAdd(){
            this.$store.commit('setVisibleAdd2',true)
            this.$nextTick(() => {
                var myCenter = new google.maps.LatLng(this.mapData.center);
                var mapProp = {
                    center:myCenter,
                    zoom:9,//缩放级数
                    mapTypeId:google.maps.MapTypeId.ROADMAP
                };
                let Dom_map=this.$refs.addModalGoogle.$refs.allmap
                let Dom_mapTool=this.$refs.addModalGoogle.$refs.mapTool
                let Dom_mapWrap=this.$refs.addModalGoogle.$refs.mapWrap
                this.mapData.mapObj = new google.maps.Map(Dom_map,mapProp);
                this.mapData.mapObj.controls[google.maps.ControlPosition.TOP_RIGHT].push(Dom_mapTool);
                this.mapData.width=this.$refs.addModalGoogle.$refs.mapWrap.clientWidth
                if(this.mapData.markers.length>0){
                    this.mapData.markers[0].setMap(null);
                    this.mapData.markers=[]
                }
                
            })
        },
        async openGoogleEdit(id){
            let res = await this.API.getSiteData({
                id:id
            })
            this.editData=res
            this.$store.commit('setVisibleEdit2',true)
            this.$nextTick(() => {
                var myCenter = new google.maps.LatLng(this.mapData.center);
                var mapProp = {
                    center:myCenter,
                    zoom:9,//缩放级数
                    mapTypeId:google.maps.MapTypeId.ROADMAP
                };
                let Dom_map=this.$refs.editModalGoogle.$refs.allmap
                let Dom_mapTool=this.$refs.editModalGoogle.$refs.mapTool
                let Dom_mapWrap=this.$refs.editModalGoogle.$refs.mapWrap
                this.mapData.mapObj = new google.maps.Map(Dom_map,mapProp);
                this.mapData.mapObj.controls[google.maps.ControlPosition.TOP_RIGHT].push(Dom_mapTool);
                this.mapData.width=this.$refs.editModalGoogle.$refs.mapWrap.clientWidth

                if(this.editData.latitude!=''&&this.editData.longitude!=''){
                    var transParam = this.UtilsFun.transformPoint(this.editData.latitude,this.editData.longitude,'google');
                    let point={lat:Number(transParam.latitude),lng:Number(transParam.longitude)}
                    this.mapData.mapObj.setCenter(point);
                    var marker = new google.maps.Marker({
                        position:point,
                        draggable:true,
                        map:this.mapData.mapObj
                        });// 创建标注
                    this.mapData.markers.push(marker);
                }
            })
        },
        showDeleteModal(data){
            let siteName = ''
            if(!data){
                this.emailType = 'barch'
                if(this.selectDatalist.length>0){
                    if(this.userType != 5){
                        this.deleteBatch()
                        return
                    }
                    siteName = this.selectDatalist.map(item=>{
                        return item.siteName
                    }).join('、')
                    this.$store.commit('setGetUserEmailCodeFlag',true)
                }else{
                    this.$message.error(this.$t('index.delete_select'))
                }
            }else{
                this.$store.commit('setGetUserEmailCodeFlag',true)
            }
            this.siteNameDelete = data || {siteName:siteName}
        },
        async deleteSub(id){
            let res = await this.API.siteDeleteBatch({
                ids:id
            })
            if(res.success){
                this.$store.commit('setGetUserEmailCodeFlag',false)
                this.$message.success(this.$t('index.control_success'))
            }else{
                this.$message.error(this.$t('index.control_fail'))
            }
            this.initTable()
        },
        async deleteBatch(){
            if(this.selectDatalist.length>0){
                let ids = this.selectDatalist.map(item => {
                    return item.ids
                })
                let res = await this.API.siteDeleteBatch({
                    ids
                })
                if(res.success){
                    this.$store.commit('setGetUserEmailCodeFlag',false)
                    this.$message.success(this.$t('index.control_success'))
                }else{
                    this.$message.error(this.$t('index.control_fail'))
                }
                this.initTable()
            }else{
                this.$message.error(this.$t('index.delete_select'))
            }
        },
        async getDictionaryBatch(){
            let res = await this.API.getDictionaryBatch({
                dictCodes:'FIRM_TYPE',
                lang:localStorage.getItem('lang')
            })
            this.typeList = res.FIRM_TYPE
        },
        async initTable(){
            this.loading = true
            let params={
                size: this.size,
                current: this.current,
                ...this.searchData
            }
            //用户管理的参数
            if(this.businessId) params.businessId=this.businessId
            if(this.userId) params.userId=this.userId

            let res = await this.API.getSiteTable(params)
            this.dataRows = res.rows || []
            this.total = res.total
            this.loading = false
        },
        showUser(data){
            this.$store.commit('setVisibleInfo',true)
            this.rowDataList = data
        },
        bindWifiSn(data){
            this.$store.commit('setVisibleBind',true)
            this.selRow_bind = data
        },
        bindWifiSnExcel(data){
            this.$store.commit('setVisibleBind2',true)
            this.selRow_bind2 = data
        },
        setPrice(data){
            this.$store.commit('setVisibleShow',true)
            this.setPriceId = data
        },
        showScope(data,row){
            this.$store.commit('setVisibleInfo',true)
            this.scopeId = data
            this.scopeData = row
        },
        gotoInverter(data){
            console.log('gotoinverter');
            this.$router.push({ path: '/inverter', query: {
                    // siteId:data.ids,
                    userId:this.userId,
                    businessId:this.businessId,
                    siteName:data.siteName
                } 
            })
        },
        uploadPage(){
            this.initTable()
        },
        returnTypeCode(val){
            let res
            this.typeList.forEach(item=>{
                if(val==item.value){
                    res = item.code
                }
            })
            return res
        },
        query(){
            this.current = 1
            this.initTable()
        },
        handleSelectionChange(val){
            this.selectDatalist = val
        },
        handleSizeChange(val) {
          this.size = val
          this.current = 1
          this.initTable()
        },
        handleCurrentChange(val) {
          this.current = val
          this.initTable()
        },
    }
}

</script>
<style lang='less' scoped>

</style>